package com.monolithiot.sso.common.util;

import java.util.ArrayList;
import java.util.List;

/**
 * 2018/11/26 Create by 郭文梁
 * HtmlUtil
 * Html文本工具类
 *
 * @author 郭文梁
 * @date 2018/11/26
 */
public class HtmlUtil {
    private static final String P_START_TAG = "<p>";
    private static final String P_END_TAG = "</p>";
    private static final String LINE_DELIMITER = "\n";
    /**
     * 默认选取前50个字作为为文章摘要
     */
    private static final int ABSTRACT_LENGTH = 100;

    /**
     * 将plain text转换为html行
     *
     * @param text plain text
     * @return html line
     */
    public static String asHtmlLine(String text) {
        if (text == null) {
            return null;
        }
        String[] split = text.split(LINE_DELIMITER);
        StringBuilder sb = new StringBuilder();
        for (String line : split) {
            sb.append(P_START_TAG).append(line).append(P_END_TAG);
        }
        return sb.toString();
    }

    /**
     * 对文章内容摘要
     *
     * @param html 文本数据
     * @return 摘要结果
     */
    public static String abstracts(String html) {
        if (html == null) {
            return null;
        }
        if (html.length() > ABSTRACT_LENGTH) {
            html = html.substring(0, ABSTRACT_LENGTH);
        }
        return asPlaintText(html);
    }

    /**
     * 去除html中的标签
     *
     * @param html html文本
     * @return plain text
     */
    public static String asPlaintText(String html) {
        return html.replaceAll("<[^>]+>", "");
    }

    /**
     * 分割行
     *
     * @param text 文本
     * @return 分割结果
     */
    public static List<String> splitLines(String text) {
        if (text == null) {
            return null;
        }
        String[] lines = text.split(LINE_DELIMITER);
        List<String> res = new ArrayList<>();
        for (String line : lines) {
            if (!isEmpty(line)) {
                res.add(line.trim());
            }
        }
        return res;
    }

    /**
     * trim后的字符串是否为空
     *
     * @param str 字符串
     * @return 是否为空
     */
    public static boolean isEmpty(String str) {
        if (str == null) {
            return true;
        } else {
            return "".equals(str.trim());
        }
    }
}
